# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'

from cherrypy import HTTPError
from configs import configs as conf
from pymongo.errors import DuplicateKeyError


class Player(object):
    def __init__(self, vid, credentials, game):
        self.vid = vid
        self.credentials = credentials
        self.game = game


class PlayerMapper(object):

    def __init__(self):
        self.foundUser = None
        self.client = conf.client

    def check(self, credential, game, password=None):
        query = {}
        query['credentials'] = credential
        query['game'] = game
        if password:
            query['password'] = password

        users = self.client.freya.players.find(query)

        count = users.count()
        if count == 1:
            self.foundUser = Player(users[0]['vid'], users[0]['credentials'], users[0]['game'])
            return True
        elif count > 1:
            return False
        elif count == 0:
            return False

    def create(self, vid, credential, game, password):
        try:
            result = self.client.freya.players.insert({'vid': vid, 'credentials': [credential], 'password': password,
                                                       'game': game})
            if result:
                return True
            else:
                return False
        except DuplicateKeyError as e:
            raise HTTPError(401, 'Wrong password')
        except Exception as e:
            raise HTTPError(503)

    def change_password(self, credential, game, new_password):
        if self.check(credential, game):
            query = {}
            query["vid"] = self.foundUser.vid

            try:
                result = self.client.freya.players.update({"vid": self.foundUser.vid}, {"$set": {"password": new_password}})
                if result['ok'] and (result['n'] == 1):
                    return True
                else:
                    raise HTTPError(500)
            except HTTPError as e:
                raise e
            except Exception as e:
                raise HTTPError(500)
        else:
            raise HTTPError(404)